/***
    Amrita ITEWS - Copyright (C) 2009 Amrita Vishwa Vidyapeetham, Amritapuri.
                                       (http://www.amrita.edu)
    ***************************************************************************
    This file is part of the Amrita ITEWS distribution.
    Amrita ITEWS is free software; you can redistribute it and/or modify it 
    under the terms of the GNU General Public License (version 2) as published
    by the Free Software Foundation AND MODIFIED BY the Amrita ITEWS exception.
    ***NOTE*** The exception to the GPL is included to allow you to distribute
    a combined work that includes Amrita ITEWS without being obliged to provide
    the source code for proprietary components outside of the Amrita ITEWS
    software. Amrita ITEWS is distributed in the hope that it will be useful, 
    but WITHOUT ANY WARRANTY; without even the implied warranty of 
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
    Public License for more details. You should have received a copy of the GNU
    General Public License and the Amrita ITEWS license exception along with 
    Amrita ITEWS if not then it can be viewed here: 
    http://itews.amrita.ac.in/license.html.

    Documentation, latest information, license and contact details are at:
    http://itews.amrita.ac.in/

    Amrita ITEWS source code can be found at:
    http://code.google.com/p/itews

    The initial code-base of Amrita ITEWS was developed by Amrita Vishwa 
    Vidyapeetham as part of the project titled,"Intelligent & Interactive 
    Telematics using Emerging Wireless Technologies for Transport Systems 
    (ITEWS)" sponsored by Technology Information Forecasting and Assessment 
    Council (TIFAC), India.
***/
package baseplatformservices;

import java.io.ByteArrayInputStream;
import java.net.ConnectException;
import java.net.HttpRetryException;
import java.net.MalformedURLException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.net.UnknownServiceException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

import org.apache.commons.httpclient.CircularRedirectException;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.NoHttpResponseException;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.knopflerfish.service.log.LogRef;

public class BlogPublisher extends Thread
{
	private static final String FEED_TITLE = "Media Play Log";
	private BasePlatformConfig config;
	private HttpClient client;
	private String mediaLogFeedURL = null;
	private String downloadLogFeedURL = null;
	private  LogRef log;
	private boolean running = true;
	private DBConnectionPool dbConnectionPool;
	private SimpleDateFormat simpleDateFormat;
	private String mediaPlayLogQuery = "SELECT * FROM media_play_log ORDER BY end_time LIMIT 1";
	private String downloadLogQuery = "SELECT * FROM media_download_log ORDER BY logtime LIMIT 1";
	private String mediaPlayLogDelete = "DELETE FROM media_play_log WHERE id=?";
	private String downloadLogDelete = "DELETE FROM media_download_log WHERE id=?";
	private String feedEntryIdQuery = "SELECT id FROM feed_entry_id";
	private String feedEntryIdUpdate = "UPDATE feed_entry_id SET id=?";
	private String feedEntryIdInsert = "INSERT INTO feed_entry_id VALUES(?)";
	private String mediaLogFeed;
	private String downloadLogFeed;
	private int feedEntryId;
	private boolean mediaLogAvltoBePublished = true;
	private boolean downloadLogAvltoBePublished = true;
	
	public BlogPublisher() throws Exception
	{
		Connection conn = null;
		PreparedStatement preparedStmt1 = null;
		PreparedStatement preparedStmt2 = null;
		ResultSet rs1 = null;
		try
		{
			log = new LogRef(Activator.bc);
			config = BasePlatformConfig.getConfig();
			dbConnectionPool = DBConnectionPool.getInstance(config.getJdbcConnectionURI());
			client = new HttpClient();
			HttpConnectionManagerParams hcp = new HttpConnectionManagerParams();
			hcp.setConnectionTimeout(config.getHttpConnTimeoutSecs()*1000);
			hcp.setSoTimeout(config.getHttpSocTimeoutSecs()*1000);
			HttpConnectionManager connManager = client.getHttpConnectionManager();
			connManager.setParams(hcp);
			String[] blogPublisherApps = config.getBlogPublisherApps();
			mediaLogFeed = blogPublisherApps[0];
			downloadLogFeed = blogPublisherApps[1];
			mediaLogFeedURL = config.getFeedURL() + mediaLogFeed + "/" + config.getTelematicsUnit();
			downloadLogFeedURL = config.getFeedURL() + downloadLogFeed + "/" + config.getTelematicsUnit();
			simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			conn = dbConnectionPool.getConnection();
			preparedStmt1 = dbConnectionPool.getPreparedStmt(conn, feedEntryIdQuery);
			rs1= preparedStmt1.executeQuery();
	    	if (rs1.next() == true)
	    	{
	    		feedEntryId = rs1.getInt(1);
	    	}
	    	else
	    	{
	    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, feedEntryIdInsert);
	    		preparedStmt2.setInt(1, 1);
	    		preparedStmt2.executeUpdate();
		    	preparedStmt2.close();
		    	preparedStmt2 = null;
	    	}
	    	rs1.close();
	    	rs1 = null;
	    	preparedStmt1.close();
	    	preparedStmt1 = null;
		}
		catch(Exception e)
		{
			log.error("BlogPublisher failed to start during initiation");
    		if (rs1 != null)
    		{
    			try {rs1.close();} catch (SQLException sqle) {} 
    			rs1 = null;
    		}
			if (preparedStmt1 != null)
    		{
    			try {preparedStmt1.close();} catch (SQLException sqle) {} 
    			preparedStmt1 = null;
    		}
			if (preparedStmt2 != null)
    		{
    			try {preparedStmt2.close();} catch (SQLException sqle) {} 
    			preparedStmt2 = null;
    		}
			if (conn != null)
			{
				try {conn.close();} catch (SQLException sqle) {}
				conn = null;
			}
			throw e;
		}
	}
	
	public void run() 
	{
		System.out.println("Blog Publisher started");
		while (running == true)
		{
			if (mediaLogAvltoBePublished == true || downloadLogAvltoBePublished == true)
			{
				publishMediaPlayLog();
				try {Thread.sleep(config.getBlogPublishIntervalSecs() * 100);} catch (InterruptedException e) {}
				publishDownloadLog();
				try {Thread.sleep(config.getBlogPublishIntervalSecs() * 100);} catch (InterruptedException e) {}
			}
			else
			{
				try {Thread.sleep(5000);} catch (InterruptedException e) {}
				mediaLogAvltoBePublished = true;
				downloadLogAvltoBePublished = true;
			}
		}
	}
	
	private void publishMediaPlayLog()
	{
		Connection conn = null;
		PreparedStatement preparedStmt1 = null;
		PreparedStatement preparedStmt2 = null;
		ResultSet rs1 = null;
		PostMethod postMethod = null;
		try 
		{
			if (mediaLogFeedURL != null)
			{
				Timestamp startTimestamp = null;
				Timestamp endTimestamp = null;
				int mediaLogSeqNo = 0;
				String routeCode = null;
				String mediaCode = null;
				String nodeCode = null;
				String triggerType = null;
				int mediaDuration = 0;
				String relativeMediaPath = null;
				String playedStatus = null;
				String startLongLat = "";
				String endLongLat = "";

				conn = dbConnectionPool.getConnection();
				preparedStmt1 = dbConnectionPool.getPreparedStmt(conn, mediaPlayLogQuery);
				rs1= preparedStmt1.executeQuery();
		    	if (rs1.next() == true)
		    	{
		    		mediaLogAvltoBePublished = true;
		    		mediaLogSeqNo = rs1.getInt(1);
		    		routeCode = rs1.getString(2);
		    		mediaCode = rs1.getString(3);
		    		nodeCode = rs1.getString(4);
	                triggerType = rs1.getString(5);
	                mediaDuration = rs1.getInt(6);
	                relativeMediaPath = rs1.getString(7);
	                playedStatus = rs1.getString(8);
					startLongLat = rs1.getString(9);
					endLongLat = rs1.getString(10);
					startTimestamp = rs1.getTimestamp(11);
		    		endTimestamp = rs1.getTimestamp(12);
		    	}
		    	else
		    	{
		    		mediaLogAvltoBePublished = false;
		    	}
		    	rs1.close();
		    	rs1 = null;
		    	preparedStmt1.close();
		    	preparedStmt1 = null;
		    	if (mediaLogAvltoBePublished == true && (routeCode != null && mediaCode != null && nodeCode != null && triggerType != null && relativeMediaPath != null && playedStatus != null && startTimestamp !=null && endTimestamp !=null))
		    	{
		    		postMethod = new PostMethod(mediaLogFeedURL);
	    			StringBuffer xmlBody = new StringBuffer(); 
					xmlBody.append("<entry>\n<title>").append(FEED_TITLE).append("</title>\n<author>\n<name>").append(config.getTelematicsUnit()).append("</name>\n</author>\n<id>").append(feedEntryId).append("</id>\n<category>").append(mediaLogFeed).append("</category>\n<content>\n");
					xmlBody.append("routecode: ");
					xmlBody.append(routeCode).append('\n');
					xmlBody.append("mediacode: ");
					xmlBody.append(mediaCode).append('\n');
					xmlBody.append("nodecode: ");
					xmlBody.append(nodeCode).append('\n');
					xmlBody.append("triggertype: ");
					xmlBody.append(triggerType).append('\n');
	                xmlBody.append("mediadur: ");
	                xmlBody.append(mediaDuration).append('\n');
	                xmlBody.append("relativemediapath: ");
	                xmlBody.append(relativeMediaPath).append('\n');
	                xmlBody.append("playedstatus: ");
	                xmlBody.append(playedStatus).append('\n');
	                xmlBody.append("startlonglat: ");
	                xmlBody.append(startLongLat).append('\n');
	                xmlBody.append("endlonglat: ");
	                xmlBody.append(endLongLat).append('\n');
					xmlBody.append("starttime: ");
					xmlBody.append(simpleDateFormat.format(startTimestamp)).append('\n');
					xmlBody.append("endtime: ");
	                xmlBody.append(simpleDateFormat.format(endTimestamp)).append('\n');
					xmlBody.append("</content>\n</entry>\n");
					ByteArrayInputStream is = new ByteArrayInputStream(xmlBody.toString().getBytes());
					InputStreamRequestEntity requestEntity = new InputStreamRequestEntity(is);
					postMethod.setRequestEntity(requestEntity);
					client.executeMethod(postMethod);
					if (postMethod.getStatusCode() == HttpStatus.SC_OK)
					{
						log.info("Published Played Media Log successfully");
			    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, mediaPlayLogDelete);
			    		preparedStmt2.setInt(1, mediaLogSeqNo);
			    		preparedStmt2.executeUpdate();
				    	preparedStmt2.close();
				    	preparedStmt2 = null;
				    	
				    	++feedEntryId;
				    	
			    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, feedEntryIdUpdate);
			    		preparedStmt2.setInt(1, feedEntryId);
			    		preparedStmt2.executeUpdate();
				    	preparedStmt2.close();
				    	preparedStmt2 = null;
					}
					else
					{
						//String response = postMethod.getResponseBodyAsString();
						log.error("Failed to publish Played Media Log: "+postMethod.getStatusCode());
					}
					postMethod.releaseConnection();
					postMethod = null;
		    	}
		    	else if (mediaLogAvltoBePublished != false)
		    	{
		    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, mediaPlayLogDelete);
		    		preparedStmt2.setInt(1, mediaLogSeqNo);
		    		preparedStmt2.executeUpdate();
			    	preparedStmt2.close();
			    	preparedStmt2 = null;
		    	}
			}
		}
		catch (NoRouteToHostException nre) 
		{
			log.debug("Blog Publisher error: " + nre + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (MalformedURLException mue) 
		{
			log.debug("Blog Publisher error: " + mue + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (ConnectException ce) 
		{
			log.debug("Blog Publisher error: " + ce + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (HttpRetryException hre) 
		{
			log.debug("Blog Publisher error: " + hre + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (SocketTimeoutException ste) 
		{
			log.debug("Blog Publisher error: " + ste + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (UnknownServiceException use) 
		{
			log.debug("Blog Publisher error: " + use + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (UnknownHostException uhe) 
		{
			log.debug("Blog Publisher error: " + uhe + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (ConnectTimeoutException cte) 
		{
			log.debug("Blog Publisher error: " + cte + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (CircularRedirectException cre) 
		{
			log.debug("Blog Publisher error: " + cre + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (HttpException he) 
		{
			log.debug("Blog Publisher error: " + he + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (NoHttpResponseException nhe) 
		{
			log.debug("Blog Publisher error: " + nhe + " URL: " +mediaLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (Exception e) 
		{
			log.debug("Blog Publisher error: " + e +" URL: " +mediaLogFeedURL);
			e.printStackTrace();
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		finally
		{
			if (postMethod != null)
			{
				postMethod.releaseConnection();
				postMethod = null;
			}
			if (rs1 != null)
			{
				try {rs1.close();} catch (SQLException e) {} 
				rs1 = null;
			}
			if (preparedStmt1 != null)
			{
				try {preparedStmt1.close();} catch (SQLException e) {} 
				preparedStmt1 = null;
			}
			if (preparedStmt2 != null)
			{
				try {preparedStmt2.close();} catch (SQLException e) {} 
				preparedStmt2 = null;
			}
			if (conn != null)
			{
				try {conn.close();} catch (SQLException e) {}
				conn = null;
			}
		}
	}
	
	private void publishDownloadLog()
	{
		Connection conn = null;
		PreparedStatement preparedStmt1 = null;
		PreparedStatement preparedStmt2 = null;
		ResultSet rs1 = null;
		PostMethod postMethod = null;
		try 
		{
			if (downloadLogFeedURL != null)
			{
				int id = 0;
				String mediaCode = null;
				int percentageDownload = 0;
				String dataRate = null;
				String isNotFound = null;
				String lastKnownStatus = null;
				String changedParams = null;
				String nodeCodeAndLatLng = null;
				Timestamp logTime = null;
				conn = dbConnectionPool.getConnection();
				preparedStmt1 = dbConnectionPool.getPreparedStmt(conn, downloadLogQuery);
				rs1= preparedStmt1.executeQuery();
		    	if (rs1.next() == true)
		    	{
		    		downloadLogAvltoBePublished = true;
		    		id = rs1.getInt(1);
		    		mediaCode = rs1.getString(2);
		    		percentageDownload = rs1.getInt(3);
		    		dataRate = rs1.getString(4);
		    		isNotFound = rs1.getString(5);
		    		lastKnownStatus = rs1.getString(6);
		    		changedParams = rs1.getString(7);
		    		nodeCodeAndLatLng = rs1.getString(8);
		    		logTime = rs1.getTimestamp(9);
		    		if (dataRate == null) dataRate = ""; 
		    		if (isNotFound == null) isNotFound = "";
		    		if (lastKnownStatus == null) lastKnownStatus = "";
		    		if (changedParams == null) changedParams = "";
		    		if (nodeCodeAndLatLng == null) nodeCodeAndLatLng = "";
		    	}
		    	else
		    	{
		    		downloadLogAvltoBePublished = false;
		    	}
		    	rs1.close();
		    	rs1 = null;
		    	preparedStmt1.close();
		    	preparedStmt1 = null;
		    	if (downloadLogAvltoBePublished == true && mediaCode != null && logTime !=null)
		    	{
		    		postMethod = new PostMethod(downloadLogFeedURL);
	    			StringBuffer xmlBody = new StringBuffer(); 
					xmlBody.append("<entry>\n<title>").append(FEED_TITLE).append("</title>\n<author>\n<name>").append(config.getTelematicsUnit()).append("</name>\n</author>\n<id>").append(feedEntryId).append("</id>\n<category>").append(downloadLogFeed).append("</category>\n<content>\n");
					xmlBody.append("mediacode: ");
					xmlBody.append(mediaCode).append('\n');
					xmlBody.append("perDownload: ");
					xmlBody.append(percentageDownload).append('\n');
					xmlBody.append("dataRate: ");
					xmlBody.append(dataRate).append('\n');
	                xmlBody.append("isNotFound: ");
	                xmlBody.append(isNotFound).append('\n');
	                xmlBody.append("lastKnownStatus: ");
	                xmlBody.append(lastKnownStatus).append('\n');
	                xmlBody.append("changedParams: ");
	                xmlBody.append(changedParams).append('\n');
	                xmlBody.append("nodeCodeAndLatLng: ");
	                xmlBody.append(nodeCodeAndLatLng).append('\n');
					xmlBody.append("logTime: ");
					xmlBody.append(simpleDateFormat.format(logTime)).append('\n');
					xmlBody.append("</content>\n</entry>\n");
					ByteArrayInputStream is = new ByteArrayInputStream(xmlBody.toString().getBytes());
					InputStreamRequestEntity requestEntity = new InputStreamRequestEntity(is);
					postMethod.setRequestEntity(requestEntity);
					client.executeMethod(postMethod);
					if (postMethod.getStatusCode() == HttpStatus.SC_OK)
					{
						log.info("Published Download Log successfully");
			    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, downloadLogDelete);
			    		preparedStmt2.setInt(1, id);
			    		preparedStmt2.executeUpdate();
				    	preparedStmt2.close();
				    	preparedStmt2 = null;
				    	
				    	++feedEntryId;
				    	
			    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, feedEntryIdUpdate);
			    		preparedStmt2.setInt(1, feedEntryId);
			    		preparedStmt2.executeUpdate();
				    	preparedStmt2.close();
				    	preparedStmt2 = null;
					}
					else
					{
						log.error("Failed to publish Download Log: "+postMethod.getStatusCode());
					}
					postMethod.releaseConnection();
					postMethod = null;
		    	}
		    	else if (downloadLogAvltoBePublished == true && (mediaCode == null || logTime == null))
		    	{
		    		preparedStmt2 = dbConnectionPool.getPreparedStmt(conn, downloadLogDelete);
		    		preparedStmt2.setInt(1, id);
		    		preparedStmt2.executeUpdate();
			    	preparedStmt2.close();
			    	preparedStmt2 = null;
		    	}
			}
		}
		catch (NoRouteToHostException nre) 
		{
			log.debug("Blog Publisher error: " + nre + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (MalformedURLException mue) 
		{
			log.debug("Blog Publisher error: " + mue + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (ConnectException ce) 
		{
			log.debug("Blog Publisher error: " + ce + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (HttpRetryException hre) 
		{
			log.debug("Blog Publisher error: " + hre + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (SocketTimeoutException ste) 
		{
			log.debug("Blog Publisher error: " + ste + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (UnknownServiceException use) 
		{
			log.debug("Blog Publisher error: " + use + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (UnknownHostException uhe) 
		{
			log.debug("Blog Publisher error: " + uhe + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (ConnectTimeoutException cte) 
		{
			log.debug("Blog Publisher error: " + cte + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (CircularRedirectException cre) 
		{
			log.debug("Blog Publisher error: " + cre + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (HttpException he) 
		{
			log.debug("Blog Publisher error: " + he + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (NoHttpResponseException nhe) 
		{
			log.debug("Blog Publisher error: " + nhe + " URL: " +downloadLogFeedURL);
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		catch (Exception e) 
		{
			log.debug("Blog Publisher error: " + e +" URL: " +downloadLogFeedURL);
			e.printStackTrace();
			try {Thread.sleep(config.getBlogPublishIntervalSecs() * 10000);} catch (InterruptedException ie) {}
		}
		finally
		{
			if (postMethod != null)
			{
				postMethod.releaseConnection();
				postMethod = null;
			}
			if (rs1 != null)
			{
				try {rs1.close();} catch (SQLException e) {} 
				rs1 = null;
			}
			if (preparedStmt1 != null)
			{
				try {preparedStmt1.close();} catch (SQLException e) {} 
				preparedStmt1 = null;
			}
			if (preparedStmt2 != null)
			{
				try {preparedStmt2.close();} catch (SQLException e) {} 
				preparedStmt2 = null;
			}
			if (conn != null)
			{
				try {conn.close();} catch (SQLException e) {}
				conn = null;
			}
		}
	}
	
	public void stopThread()
	{
		running = false;
		System.out.println("Blog Publisher stopped");
	}
}
